package com.zlf.mvc.controller;

import com.github.pagehelper.PageInfo;
import com.zlf.constant.CrowdConstant;
import com.zlf.entity.Role;
import com.zlf.service.api.RoleService;
import com.zlf.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author ：张利锋
 * @date ：Created in 2020/11/16 15:34
 * @description： TOOD
 * @version: 1.0
 */
@Controller
public class RoleController {
    @Autowired
    RoleService roleService;

    //注解方式实现权限控制
    //@PreAuthorize("hasRole('部长') or hasRole(asd)")
    @PreAuthorize("hasRole('部长')")
    @RequestMapping("/role/get/page/info")
    @ResponseBody
    public ResultEntity<PageInfo<Role>> getPageInfo(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        PageInfo<Role> pageInfo = roleService.getPageInfo(keyword, pageNum, pageSize);
        return ResultEntity.successWithData(pageInfo);
    }

    @RequestMapping("/role/save")
    @ResponseBody
    @PreAuthorize("hasAuthority('role:add')")
    public ResultEntity<String> saveRole(Role role) {
        if ("".equals(role.getName())){
            return ResultEntity.failed(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        roleService.saveRole(role);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/role/update")
    @ResponseBody
    public ResultEntity<String> updateRole(Role role)  {
        if ("".equals(role.getName())){
            return ResultEntity.failed(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        roleService.updateRole(role);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/role/remove")
    @ResponseBody
    @PreAuthorize("hasAuthority('role:delete')")
    public ResultEntity<String> removeRole(@RequestBody List<Integer> roleIdList)  {
        if (roleIdList.size()==0){
            return ResultEntity.failed(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        roleService.removeRole(roleIdList);
        return ResultEntity.successWithoutData();
    }

}
